using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using Pinwheel.Kernel;
using Pinwheel.Service.Protocol;

namespace Pinwheel.Service
{
    public partial class WatchdogBase : ServiceBase, IServiceInstance
    {
        private PID m_GatewayPID;
        
        public override void Create(IServiceManager serviceManager, IMessageQueue<ServiceMessage> messageQueue)
        {
            base.Create(serviceManager, messageQueue);
            m_GatewayPID = ServiceManager.StartNewService<GatewayBase>("Gateway");
        }

        public override int Init()
        {
            int code = base.Init();
            
            RegisterApi("Start", Start);
            
            RegisterApi("Open", Open);
            RegisterApi("Close", Close);
            
            RegisterApi("Heartbeat", Heartbeat);
            
            RegisterApi(BindAgent);
            
            return code;
        }

        private async ValueTask<IMessage> Start(ServiceMessage message)
        {
            return await Call(m_GatewayPID, message);
        }
        
        private ValueTask<IMessage> Open(ServiceMessage message)
        {
            throw new NotImplementedException();
        }
        
        private async ValueTask<IMessage> Close(ServiceMessage message)
        {
            
            return null!;
        }
        
        private async ValueTask<IMessage> Heartbeat(ServiceMessage message)
        {
            if (message.Message is Heartbeat heartbeat)
            {
                // var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                // Log.Info($"[{Alias}]Receive heartbeat from {now - heartbeat.Value}[{now}][{heartbeat.Value}]");
                return heartbeat;
            }
            return null!;
        }
        
        private async ValueTask<IMessage> BindAgent(ServiceMessage message)
        {
            return null!;
        }
    }
}